import logging
from flask import Blueprint, request
from flask import jsonify
from sqlalchemy.exc import IntegrityError

from airflow.models.idata_config import Config
from airflow.configuration import conf
from airflow.www.api import exception_handle

log = logging.getLogger(__name__)

api_speech_config = Blueprint('api_speech_config', __name__)


@api_speech_config.route('/config/<int:id>', methods=['GET'])
@exception_handle
def get_config(id):
    config = Config.get_by_id(id)
    if config:
        return jsonify(code=0, message='ok', data=config.to_json())
    else:
        return jsonify(code=404, message='not found', data=None)


@api_speech_config.route('/config', methods=['GET'])
@exception_handle
def query_config():
    page = request.values.get('page', 1, type=int)
    section = request.values.get("section", type=str, default=None)
    result = Config.query_page(page, section)
    result.items = list(map(Config.to_json, result.items))
    result = result.to_json()
    return jsonify(code=0, message='ok', data=result)


@api_speech_config.route('/conf_env', methods=['GET'])
@exception_handle
def conf_env():
    import os
    data = dict()
    for key in os.environ.keys():
        data[key] = os.environ.get(key)
    return jsonify(code=0, message='ok', data=data)


@api_speech_config.route('/conf', methods=['GET'])
@exception_handle
def get_conf():
    section = request.values.get("section", type=str, default=None)
    key = request.values.get("key", type=str, default=None)
    if section and key:
        return jsonify(code=0, message='ok', data=conf.get(section, key))
    else:
        return jsonify(code=400, message='section or key is null', data=None)


@api_speech_config.route('/config', methods=['POST'])
@exception_handle
def insert():
    data = request.get_json()
    config = Config(**data)
    if not config.section or not config.key or not config.value:
        return jsonify(code=400, message='section or key or value is null', data=None)
    try:
        config.insert()
    except IntegrityError as err:
        return jsonify(code=500, message=str(err), data=None)
    return jsonify(code=0, message='ok', data=config.to_json())


@api_speech_config.route('/config/<int:config_id>', methods=['PUT'])
@exception_handle
def update(config_id):
    data = request.get_json()
    if 'id' not in data:
        data['id'] = config_id
    config = Config(**data)
    if not config.section or not config.key or not config.value:
        return jsonify(code=400, message='section or key or value is null', data=None)
    config.update()
    return jsonify(code=0, message='ok', data=config.to_json())


@api_speech_config.route('/config/<int:config_id>', methods=['DELETE'])
@exception_handle
def delete(config_id):
    Config.delete(config_id)
    return jsonify(code=0, message='ok', data=None)
